package hashtable;

import java.util.TreeMap;

public class HashTable<K,V> {

    private TreeMap<K,V>[] hashTable;
    private int m;
    private int size;

    public HashTable(int m){
        this.m = m;
        hashTable = new TreeMap[m];
        for(int i = 0 ; i < m ; i++){
            hashTable[i] = new TreeMap<>();
        }
        this.size = 0;
    }

    public HashTable(){
        this(97);
    }

    //哈希函数：返回索引
    private int hash(K key){
        return (key.hashCode() & 0x7fffffff) % m;
    }

    public int getSize(){
        return size;
    }

    public void add(K key,V value){
        TreeMap<K,V> map = hashTable[hash(key)];

        if(map.containsKey(key)){
            //覆盖
            map.put(key,value);
        } else{
            map.put(key,value);
            size++;
        }
    }

    public V remove(K key){
        TreeMap<K,V> map = hashTable[hash(key)];
        V ret = null;
        if(map.containsKey(key)){
            ret = map.remove(key);
            size--;
        }
        return ret;
    }

    public void set(K key,V value){
        //这个方法就是为了覆盖值
        TreeMap<K,V> map = hashTable[hash(key)];
        if(!map.containsKey(key)){
            throw new IllegalArgumentException("hashtable目标没有这个key");
        }
        map.put(key,value);
    }

    public boolean contains(K key){
        TreeMap<K,V> map = hashTable[hash(key)];
        return map.containsKey(key);
    }

    public V get(K key){
        return hashTable[hash(key)].get(key);
    }
}
